package com.sjr.easy.chat.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.sjr.easy.chat.model.Conversation;
import com.sjr.easy.chat.service.ConversationService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.sjr.easy.chat.repo.ConversationRepo;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class ConversationServiceImpl implements ConversationService {

    @Autowired
    private ConversationRepo conversationRepo;

    @Override
    public void createConversation(Integer type, Long uid1, Long uid2, Long chatGroupId) {
        Conversation conversation = new Conversation();

        conversation.setType(type);
        conversation.setCreateTime(new Date());
        if (chatGroupId == null) {
            List<Long> idList = Lists.newArrayList(uid1, uid2);
            idList.sort(Long::compare);

            conversation.setUid1(idList.get(0));
            conversation.setUid2(idList.get(1));
        } else {
            conversation.setUid1(uid1);
            conversation.setChatGroupId(chatGroupId);
        }
        conversationRepo.save(conversation);
    }

    @Override
    public Conversation getConversation(Long uid1, Long uid2, Long chatGroupId) {
        Conversation conversation = new Conversation();

        if (chatGroupId == null) {
            List<Long> idList = Lists.newArrayList(uid1, uid2);
            idList.sort(Long::compare);
            conversation.setUid1(idList.get(0));
            conversation.setUid2(idList.get(1));
        } else {
            conversation.setUid1(uid1);
            conversation.setChatGroupId(chatGroupId);
        }

        QueryWrapper<Conversation> queryWrapper = new QueryWrapper<>(conversation);
        return conversationRepo.getOne(queryWrapper);
    }

    @Override
    public List<Conversation> getByIdList(List<Long> idList) {
        log.info("idList:{}", JSON.toJSONString(idList));
        if (CollectionUtils.isEmpty(idList)) {
            return Lists.newArrayList();
        }
        return conversationRepo.listByIds(idList);
    }
}
